<?php


class Picture extends AdminBase {

	public function index(){
		$data['list']=$this->db->get('picture')->result_array();
		foreach ($data['list'] as $k=>$v){
			$data['list'][$k]['image']=$this->GetImg($v['img_id']);
		}
		$this->load->view('picture/index',$data);
	}

	public function add(){
	         if ($this->post()){
				$post=$this->input->post();
				unset($post['file']);
				$res=$this->db->insert('picture',$post);
				if ($res){
					$this->show(array('code'=>1,'msg'=>'添加成功'));
				}else{
					$this->show(array('code'=>0,'msg'=>'添加失败'));
				}
			}
		$this->load->view('picture/add');
	}

	public function edit(){
		if ($this->post()){
			$post=$this->input->post();
			unset($post['file']);
			$res=$this->db->where('id',$post['id'])->update('picture',$post);
			if ($res){
				$this->show(array('code'=>1,'msg'=>'更新成功'));
			}else{
				$this->show(array('code'=>0,'msg'=>'更新失败'));
			}

		}
		$where['id']=$this->GetId();
		$data['list']=$this->db->where($where)->get('picture')->row_array();
		$data['list']['image']=$this->GetImg($data['list']['img_id']);
		$this->load->view('picture/edit',$data);
	}

	public function upload(){
		$data=$this->uploadfile();
		if ($data['code']==1){
			$file['url']=$data['url'].$data['upload_data']['file_ext'];
			$file['ext']=$data['upload_data']['file_ext'];
			$this->db->insert('file', $file);
			$id=$this->db->insert_id();
			$this->show(array('code'=>1,'url'=>'/'.$file['url'],'img_id'=>$id));
		}else{
			$this->show(array('code'=>0,'msg'=>'上传失败'));
		}
	}

	public function delimg(){
		$id=$this->PostId();
		//开始事务
		$this->db->trans_begin();
		$info=$this->db->where('id',$id)->get('file')->row_array();
		unlink($info['url']);
		$this->db->where('id',$id)->delete('file');
		if ($this->db->trans_status() === FALSE){
			$this->db->trans_rollback();
			$this->show(array('code'=>0,'msg'=>'删除失败'));
		}else{
			$this->db->trans_commit();
			$this->show(array('code'=>1,'msg'=>'删除成功'));
		}
	}


	public function del(){
        $id=$this->PostId();
        $where['id']=$id;
		$this->db->trans_begin();
		$img=$this->db->where($where)->get('picture')->row_array();
		$info=$this->db->where('id',$img['img_id'])->get('file')->row_array();
		unlink($info['url']);
		$this->db->delete('picture', array('id'=>$id));
		if ($this->db->trans_status() === FALSE){
			$this->db->trans_rollback();
			$this->show(array('code'=>0,'msg'=>'删除失败'));
		}else{
			$this->db->trans_commit();
			$this->show(array('code'=>1,'msg'=>'删除成功'));
		}

	}


}
